#include "stdafx.h"
#include "soundex.h"
#include <string.h>
#include <ctype.h>

char* soundex(char* word)
{
	int cLength,lastCharCode,cCharCode,sourceLength;
	char* sdx;
	sdx = new char[5];
	*sdx = *word;
	cLength = 1;
	lastCharCode = getCharDigit(*word);
	sourceLength = strlen(word);
	for(int i = 1; i < sourceLength; i++)
	{
		if(cLength == 4)
			break;
		cCharCode = getCharDigit(*(word + i));
		if(cCharCode == -2)
			break;
		switch(cCharCode)
		{
		case 0:
			continue;
			break;

		case -1:
			lastCharCode = 0;
			continue;
			break;

		default:
			if(cCharCode != lastCharCode)
			{
				*(sdx + cLength) = getCharDigit(*(word + i)) + 48;
				lastCharCode = getCharDigit(*(word + i));
				cLength++;
			}
			else
				continue;
		}
	}
	if(cLength < 4)
		for(int i = cLength; i <=3; i++)
			*(sdx + i) = '0';
	*(sdx + 4) = '\0';
	return sdx;
}

void soundex(char* word,char* hashCode)
{
	int cLength,lastCharCode,cCharCode,sourceLength;
	hashCode = new char[SOUNDEX_LENGTH + 1];
	*hashCode = toupper(*word);
	cLength = 1;
	lastCharCode = getCharDigit(*word);
	sourceLength = strlen(word);
	for(int i = 1; i < sourceLength;i++)
	{
		if(cLength == 4) 
			break;
		cCharCode = getCharDigit(*(word + i));
		if(cCharCode == 2) 
			break;
		switch(cCharCode)
		{
		case 0:
			continue;
			break;

		case -1:
			lastCharCode = 0;
			continue;
			break;

		default:
			{
				if(cCharCode != lastCharCode)
				{
					*(hashCode + cLength) = cCharCode + 48;
					lastCharCode = cCharCode;
					cLength++;
				}
				else
					continue;
			}
		}
	}
	if(cLength < SOUNDEX_LENGTH)
		for(int i = cLength; i <= SOUNDEX_LENGTH - 1; i++)
			*(hashCode + i) = '0';
	*(hashCode + SOUNDEX_LENGTH) = '\0';
}

int getCharDigit(char c)
{
	switch(c)
	{
	case ' ':
		return -2;

	case 'b':
	case 'f':
	case 'p':
	case 'v':
		return 1;

	case 'c':
	case 'g':
	case 'j':
	case 'k':
	case 'q':
	case 's':
	case 'x':
	case 'z':
		return 2;

	case 'd':
	case 't':
		return 3;

	case 'l':
		return 4;

	case 'm':
	case 'n':
		return 5;

	case 'r':
		return 6;

	case 'a':
	case 'e':
	case 'i':
	case 'o':
	case 'u':
	case 'y':
		return -1;

	case 'h':
	case 'w':
		return 0;

	default: return 0; 
	}
}